<script setup>
	import {
		reactive,
		nextTick,
		ref
	} from 'vue'

	import {
		jumpTo,
		back,
		dateFormatter
	} from '@/utils/common'

	// import {
	// 	useSocket
	// } from "@/utils/client";

	import dayjs from "dayjs";

	import {
		useStore
	} from "@/stores/index"
	const userStore = useStore()

	import {
		useAudio
	} from '@/utils/audioPlay'
	const userAudio = useAudio()

	import {
		useVideo
	} from '@/utils/videoPlay'
	const userVideo = useVideo()


	import http from '@/api/chatsApi'
	import userApi from '@/api/userAPI'

	import {
		onLoad,
		onShow,
		onReady,
		onUnload,
		onBackPress
	} from "@dcloudio/uni-app";
	// import {
	// 	forEach
	// } from 'lodash';


	const data = reactive({
		current: 1,
		scrollTop: 0,
		statusLineHeight: 0,
		triggered: false,

		days: 1,
		page: 1,
		lastId: 0,
		total: 0,
		last_unread_id: 0,
		last_unread_num: 0,

		list: [],

		completeFunc: null,
		startScroll: false,

		userInfo: userStore.user.userInfo,

		gift: [1],
		isAudio: true,
		text: `只是大多数人总是不想承认现实
		希望自己可以是可以忽略客观因素的虚幻英雄，
		由此其实也正好证明了大多数人的愚昧
		而通过他们的愚昧也就能预判他们未来几年的固
		化阶层那他们就是天生的供给品难听点还有两
		个字祭品，只有他们自己不这么认为
		你也必须不能让他们醒盹，他们才能唯我独尊的
		去牺牲去供给
		`,

		group_num: 0,
		private_num: 0,
		public_num: 0,

		chatCount: {
			days: {
				public_num: {
					text_num: 0,
					picture_num: 0,
					video_num: 0,
					group_num: 0,
					voice_num: 0
				},
				private_num: {
					text_num: 0,
					picture_num: 0,
					video_num: 0,
					group_num: 0,
					voice_num: 0
				},
				group_num: {
					text_num: 0,
					picture_num: 0,
					video_num: 0,
					group_num: 0,
					voice_num: 0
				},
				now_count: 0
			},
			count_num: 0
		},

		startTime: "",
		showImg: false,
		imgSrc: "",

		isShow: true
	})


	// const scrollToBottom = () => {
	// 	// 自动滚动到底部
	// 	nextTick(() => {
	// 		const query = uni.createSelectorQuery()
	// 		query.select('.dialogue-box').boundingClientRect()
	// 		query.select('.dialogue-box-content').boundingClientRect()
	// 		query.exec(res => {
	// 			const scrollViewHeight = res[0].height
	// 			const scrollContentHeight = res[1].height

	// 			if (scrollContentHeight > scrollViewHeight) {
	// 				const scrollTop = scrollContentHeight - scrollViewHeight
	// 				data.scrollTop = scrollTop
	// 			}
	// 		})
	// 	})
	// }

	// const client = useSocket();


	// onPullDownRefresh(async () => {
	// 	// setTimeout(() => {
	// 	// 
	// 	// }, 2000)

	// 	// data.isRefreshing = true

	// 	data.page++;

	// 	await loadData()

	// 	uni.stopPullDownRefresh();
	// })

	function onPulling(e) {
		// console.log("onpulling", e);
	}


	onShow(() => {

		// uni.setNavigationBarColor({
		// 	frontColor: '#000', // 前景色值，包括按钮、标题、状态栏的颜色
		// 	backgroundColor: '#fff', // 背景颜色值，包括状态栏背景颜色              
		// });
	})

	// async function onRefresh() {

	// 	data.page++;

	// 	await loadData()

	// 	data.triggered = false;
	// }

	// function onRestore() {
	// 	data.triggered = 'restore'; // 需要重置
	// 	// console.log("onRestore");
	// }

	// function onAbort() {
	// 	// console.log("onAbort");
	// }

	let paging = ref(null);

	onLoad(async (options) => {

		data.days = +options.days;

		// paging.value.reload(true);

		data.triggered = false;

		//获取用户信息
		await userStore.user.getUserinfo()

		data.userinfo = userStore.user.userInfo


		//个人信息记录
		const res2 = await http.chatCount(data.days);
		data.chatCount = res2.data;


		const res1 = await http.readNum(data.days);
		data.group_num = res1.data.group_num;
		data.private_num = res1.data.private_num;
		data.public_num = res1.data.public_num;

		// await client.connect((socket) => {

		// 	// socket.on('say', async function(item) {

		// 	// 	console.log('say', item)

		// 	// })

		// 	// socket.on('msg', async function(item) {

		// 	// 	console.log('msg', item)

		// 	// })

		// 	// socket.on('join', (room) => {
		// 	// 	socket.join(room);
		// 	// 	console.log(`客户端已加入房间 ${room}`);
		// 	// });

		// 	socket.on('event', async function(item) {

		// 		const row = await userStore.user.findAvatar(item.from_user_id);

		// 		nextTick(() => {
		// 			data.list.push({
		// 				isMy: false,
		// 				id: item.id,
		// 				duration: item.duration,
		// 				group_id: item.room_id,
		// 				member_id: item.from_user_id,
		// 				type: item.type,
		// 				value: item.content,
		// 				avatar: row.avatar,
		// 				realname: row.realname,
		// 				sex: row.sex,
		// 				created_at: item.created_at
		// 			})

		// 			// scrollToBottom();
		// 		})
		// 	});

		// 	// console.log(socket);

		// });

		// await loadData();
	})

	onUnload(() => {
		//移除音频
		userAudio.disconnect()

		// client.disconnect()
	})

	onReady(() => {
		let menuButtonInfo = uni.getMenuButtonBoundingClientRect() //获取胶囊坐标信息
		data.statusLineHeight = menuButtonInfo.top
		//给输入框高度赋值　（不乘2的原因是不管什么手机获取到的胶囊的坐标单位就是px，输入框从胶囊top位置显示，文字用这个方法可以试着设置一下line-height跟胶囊一样高应该也行）

		// console.log(data.statusLineHeight);
	})

	onBackPress((options) => {
		console.log('from:' + options.from)
		return true;
	})

	const goBack = () => {
		//移除音频
		userAudio.disconnect()

		// jumpTo("/pages/room/index?days=" + data.days)
		back();
	}

	// const loadData = async () => {
	// 	const res = await http.history(data.days, data.page,0, data.lastId)
	// 	data.total = res.data.total;
	// 	data.lastId = res.data.last_id;
	// 	await initSelect(res.data.history.data);
	// }

	const scrolltolower = async (e) => {
		// data.page++;

		// await loadData()
	}

	const initSelect = async (items) => {
		if (Array.isArray(items)) {
			var rows = Array.from(items).map((item) => {
				return {
					...item,
					isMy: data.userInfo.id == item.member_id,
					startTime: ""
					// avatar: "",
					// realname: "",
					// sex: "0",
				}
			})

			for (let i = 0; i < rows.length; i++) {

				if (data.startTime) {
					let time1 = dayjs(data.startTime)

					let time2 = dayjs(rows[i].created_at)


					// console.log(time2.diff(time1, "minute"));

					if (time2.diff(time1, "minute") < 5) {

					} else {
						data.startTime = rows[i].created_at;
						rows[i].startTime = dayjs(rows[i].created_at).format("HH:mm:ss");
					}
				} else {
					rows[i].startTime = dayjs(rows[i].created_at).format("HH:mm:ss");
					data.startTime = rows[i].created_at;
				}



			}

			// for (let i = 0; i < rows.length; i++) {
			// 	let res = await userStore.user.findAvatar(rows[i].member_id);
			// 	rows[i].avatar = res.avatar;
			// 	// rows[i].realname = res.realname
			// 	// rows[i].sex = res.sex
			// }

			return rows;

			// return rows.reverse();


			// if (data.page > 1) {

			// 	let dataList = rows.reverse();

			// 	data.list.unshift(...dataList);
			// } else {
			// 	data.list = rows.reverse();

			// 	// scrollToBottom();
			// }



			// data.list = data.list.concat(rows.reverse());
			// console.log(data.list);


			// if (data.page > 1) {
			// 	// data.list = data.list.concat(rows);
			// } else {
			// 	//反转数据
			// 	data.list = data.list.unshift(rows.reverse())
			// 	// data.list = rows;
			// }
		} else {
			// data.list = [];
			// if (data.page > 1) {

			// } else {
			// 	data.list = [];
			// }

			return [];
		}

		// 
	}

	const handleAdd = async (item) => {

		const member_id = data.userInfo.id;
		const to_user_id = data.userInfo.to_user_id;

		let duration = 0;
		if (item.duration) {
			duration = item.duration
		}

		let url = "";
		if (item.url) {
			url = item.url;
		} else if (item.text) {
			url = item.text;
		}

		const currTime = dateFormatter();

		// client.event({
		// 	id: item.id,
		// 	from_user_id: member_id,
		// 	to_user_id: to_user_id,
		// 	content: url,
		// 	type: item.type,
		// 	duration: duration,
		// 	created_at: currTime
		// })

		const row = await userStore.user.findAvatar(member_id);

		nextTick(() => {
			data.list.push({
				isMy: true,
				id: item.id,
				duration: duration,
				to_member_id: to_user_id,
				member_id: member_id,
				type: item.type,
				value: url,
				avatar: row.avatar,
				realname: row.realname,
				sex: row.sex,
				created_at: currTime
			})

			// scrollToBottom();
		})


	}

	const goGroup = () => {
		jumpTo("/pages/exclusive/group?days=" + data.days)
	}

	const goPublic = () => {
		jumpTo("/pages/exclusive/public?days=" + data.days)
	}

	const getSex = () => {
		switch (+data.userInfo.sex) {
			case 0:
			default:
				return "";
			case 1:
				return "先生";
			case 2:
				return "女士";
		}
	}

	async function queryList(pageNo, pageSize) {
		// 组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
		// 这里的pageNo和pageSize会自动计算好，直接传给服务器即可
		// 模拟请求服务器获取分页数据，请替换成自己的网络请求
		const params = {
			pageNo: pageNo,
			pageSize: pageSize,
		}

		// console.log(params)
		if (pageNo == 1) {
			// 初始化时间
			data.startTime = ""
		}

		// if (data.last_unread_num > 0) {
		// 	pageSize = data.last_unread_num;
		// 	data.lastId = data.last_unread_id;
		// }

		const res = await http.history(data.days, pageNo, pageSize, data.lastId).catch(res => {

			// 如果请求失败写this.$refs.paging.complete(false);
			// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
			// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
			paging.value.complete(false);
		})
		data.total = res.data.total;
		// data.lastId = res.data.last_id;

		// data.last_unread_id = res.data.last_unread_id;
		// data.last_unread_num = res.data.last_unread_num;


		const rows = await initSelect(res.data.history.data);

		// const rows = [];

		// 将请求的结果数组传递给z-paging
		paging.value.complete(rows);

		if (data.startScroll) {
			if (data.completeFunc) {
				data.completeFunc();
			}
		}


		// this.$request.queryChatList(params).then(res => {
		// 	// 将请求的结果数组传递给z-paging
		// 	this.$refs.paging.complete(res.data.list);
		// }).catch(res => {
		// 	// 如果请求失败写this.$refs.paging.complete(false);
		// 	// 注意，每次都需要在catch中写这句话很麻烦，z-paging提供了方案可以全局统一处理
		// 	// 在底层的网络请求抛出异常时，写uni.$emit('z-paging-error-emit');即可
		// 	this.$refs.paging.complete(false);
		// })
	}

	const previewImage = ref(null);

	function preview(src) {
		// //先下载图片
		// uni.getImageInfo({
		// 	src: src,
		// 	success: function(image) {
		// 		// console.log(image)

		// 		data.showImg = true;
		// 		data.imgSrc = image.path;

		// 	}
		// })

		data.imgSrc = src;

		nextTick(() => {
			// if(previewImage.value){
			// 	previewImage.value.open(src); // 传入当前选中的图片地址(小程序必须添加$nextTick，解决组件首次加载无图)
			// }
			data.showImg = true;
		})

		// uni.previewImage({
		// 	current: 0,
		// 	urls: [src],
		// 	showmenu: false
		// })

		// data.showImg= true;
		// data.imgSrc = src;

	}

	function beforeleave() {
		data.showImg = false
	}

	// function goUnRead() {
	// 	data.startScroll = true;

	// 	reload(function() {

	// 		setTimeout(() => {
	// 			paging.value.scrollToTop();
	// 			data.startScroll = false;

	// 		}, 1000);

	// 	});

	// }

	// function reload(callback) {
	// 	data.completeFunc = callback;
	// 	paging.value.reload();
	// }
</script>

<template>
	<!-- 	<u-mask :show="data.showImg" @click="data.showImg = false">
		<view class="warp"> -->
	<!-- <view class="rect" @tap.stop></view> -->
	<!-- <u-image :src="data.imgSrc" style="width: 100vw;padding: 10rpx;" mode="aspectFill" alt=""></u-image>
		</view>
	</u-mask> -->
	<view v-if="data.showImg">
		<page-container :show="data.showImg" @beforeleave="beforeleave">
			<q-previewImage ref="previewImage" :urls="[data.imgSrc]" @close="beforeleave"></q-previewImage>
		</page-container>
	</view>

	<view class="content">
		<!-- use-chat-record-mode：开启聊天记录模式 -->
		<!-- safe-area-inset-bottom：开启底部安全区域适配 -->
		<!-- bottom-bg-color：设置slot="bottom"容器的背景色，这里设置为和chat-input-bar的背景色一致 -->
		<z-paging ref="paging" :fixed="false" empty-tips="暂无交互数据" v-model="data.list"
			auto-show-back-to-top @query="queryList">
			<!-- 顶部提示文字 -->
			<template #top>
				<view class="safeAres"></view>
				<view class="header">
					<!-- <image class="back" @click="back" src="/static/icon/back.png" mode="aspectFit" /> -->
					<uni-icons class="back" type="back" @click="goBack" size="24" color="#828282"></uni-icons>
					<image src="https://vedio.soullightstheworld.com/video/afa18af201eb02c9914256159f995f85.jpg"
						mode="aspectFit" />
					<view class="back" style="width: 24px;">
					</view>
				</view>
				<view class="avatar">
					<image class="myAvatar border-1px" :src="data.userInfo.avatar"
						@click="preview(data.userInfo.avatar)" mode="scaleToFill" />
					<view class="mainTitle">
						<view style="font-size: 20rpx;font-weight: 400;padding-bottom: 10rpx;">
							{{data.userInfo.realname}}&nbsp;{{getSex()}} IVMCR专属定制室·特权定制\n
						</view>
						<text>IVMCR Exclusive Customization Room</text>
					</view>
				</view>

				<view class="nav">
					<view>
						<text>私人
							<text v-if="data.private_num>0" class="icon">{{data.private_num}}</text>
							<text v-else class="icon"></text>
						</text>
					</view>

					<!--<view @click="goPublic">
						<text>开放式定制拆解过程
							<text class="icon">{{data.public_num}}</text>
						</text>
					</view> -->
					<!-- <view v-if="data.userInfo.to_user_id" :class="{ isActive: true }">
						<text>私人
							<text class="icon">{{data.private_num}}</text>
						</text>
					</view> -->
					<!-- <view @click="goGroup">
						<text>分组
							<text class="icon">{{data.group_num}}</text>
						</text>
					</view> -->
				</view>

				<!-- <text class="title">本天人数89人</text> -->
				<view style="display:flex; justify-content: center; position: relative;">
					<text class="title">
						{{
				    `私人交互：${data.chatCount.days.private_num.voice_num}次语音交互  ${data.chatCount.days.private_num.video_num}次视频交互  ${data.chatCount.days.private_num.text_num}次文字交互  ${data.chatCount.days.private_num.group_num}次资料交互  ${data.chatCount.days.private_num.picture_num}次图片交互
				    本日${data.userInfo.realname}&nbsp;${getSex()}定制总计交互次数：${data.chatCount.days.now_count}次
				    截止到目前${data.userInfo.realname}&nbsp;${getSex()}整体定制的交互次数为：${data.chatCount.count_num}次`
				    }}
					</text>

					<!-- <view style="position: absolute;right: 20rpx; bottom: -30rpx; z-index: 10; background-color: #f6f6f6;color:#26a866;padding: 10rpx 20rpx;border-radius: 50px;"   v-if="data.last_unread_num>0" @click="goUnRead">
						<u-icon name="arrow-left"></u-icon> {{data.last_unread_num}}条新消息
					</view> -->
				</view>
				<!-- 公开交互：${data.chatCount.days.public_num.voice_num}次语音交互  ${data.chatCount.days.public_num.video_num}次视频交互  ${data.chatCount.days.public_num.text_num}次文字交互  ${data.chatCount.days.public_num.group_num}次资料交互  ${data.chatCount.days.public_num.picture_num}次图片交互 -->
				<!-- 分组交互：${data.chatCount.days.group_num.voice_num}次语音交互  ${data.chatCount.days.group_num.video_num}次视频交互  ${data.chatCount.days.group_num.text_num}次文字交互  ${data.chatCount.days.group_num.group_num}次资料交互  ${data.chatCount.days.group_num.picture_num}次图片交互 -->
			</template>
			<view style="height: 80rpx;"></view>
			<view v-for="(item,index) in data.list" :key="index" style="position: relative;">
				<view style="padding: 0 34rpx; ">
					<view v-if="item.startTime" class="time">
						{{item.startTime }}
					</view>
					<view class="message" :class="{ isMy: item.isMy }" :id="'message-' + index">
						<image class="avatar border-1px" :src="item.member_avatar" @click="preview(item.member_avatar)"
							mode="scaleToFill" />
						<!-- 			<uni-msg v-if="item.isAudio" :audio="item.isAudio" :src="item.src" :audioSecond="item.audioSecond"
					:isMy="item.isMy" /> 
				<uni-msg v-else :text="item.value" :isMy="item.isMy" /> -->

						<view>
							<view :style="{textAlign:item.isMy ? 'right;font-size: 18rpx;':'left;font-size: 18rpx;'}">
								{{item.member_username}}
							</view>

							<template v-if="item.type == 1">
								<uni-msg :text="item.value" :isMy="item.isMy" />
							</template>
							<template v-else-if="item.type == 2">
								<uni-msg :src="item.value" :isMy="item.isMy" @previewImage="preview" />
							</template>
							<template v-else-if="item.type == 3">
								<uni-msg :video="item.value" :coverUrl="item.cover_url" :isMy="item.isMy" />
							</template>
							<template v-else-if="item.type == 4">
								<uni-msg :audio="1" :src="item.value" :id="item.id" :isRead="item.is_read"
									:duration="item.duration" :isMy="item.isMy" />
							</template>
							<template v-else-if="item.type == 5">
								<uni-msg :gift="item.value" :realname="data.userInfo.realname + ' ' + getSex()"
									:private="1" :isMy="item.isMy" />
							</template>
						</view>
					</view>
				</view>
			</view>
			<!-- 底部聊天输入框 -->
			<template #bottom>
			</template>
			<template #empty>
				<z-paging-empty-view slot="empty" empty-view-text="暂无交互数据"></z-paging-empty-view>
			</template>
		</z-paging>
	</view>
</template>

<style lang="scss" scoped>
	.content {
		// position: relative;
		position: relative !important;
		top: 0px !important;

		height: 100%;

		:deep(.zp-l-text-rpx) {
			font-size: 18rpx;
		}
		
		:deep(.zp-back-to-top-rpx) {
			width: 60rpx;
			height: 60rpx;
		}
	}
	
	.no-border-button {
	  border: none !important;
	}

	page {
		position: relative !important;
		top: 0px !important;
	}

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.message {
		display: flex;
		margin-bottom: 40rpx;

		&.isMy {
			flex-direction: row-reverse;

			// justify-content: flex-end;
			.avatar {
				margin-left: 26rpx;
			}
		}

		.avatar {
			margin-right: 26rpx;
			width: 80rpx;
			height: 80rpx;
			box-sizing: border-box;
			border: 1rpx solid #d6d6d6;
			border-radius: 17rpx;
			background: rgb(255, 255, 255);
		}
	}

	.myAvatar {
		width: 80rpx;
		height: 80rpx;
		box-sizing: border-box;
		border: 1rpx solid #d6d6d6;
		border-radius: 17rpx;
	}

	.page {
		display: flex;
		flex-direction: column;
		height: 100%;

		.container {
			flex: 1;
			overflow: hidden;

			.main {
				//height: calc(100% - 518rpx);
				// background-color: #ff0;
				height: 100%;

				.content {
					padding: 40rpx 34rpx 40rpx;
				}
			}

		}

		// :deep(.footer) {
		// 	position: relative !important;
		// }

		// .footer {
		// 	.wrap {
		// 		display: flex;
		// 		align-items: center;
		// 		padding: 24rpx 36rpx;
		// 		background-color: #fff;

		// 		.inner {
		// 			flex: 1;
		// 		}

		// 		image {
		// 			height: 46rpx;
		// 			width: 46rpx;
		// 			margin-left: 24rpx;
		// 		}
		// 	}
		// }
	}


	.safeAres {
		padding-top: env(safe-area-inset-top)
	}

	.header {
		// padding-top: 40rpx;

		padding-top: var(--status-bar-height); //是计算状态栏的高度
		padding-top: calc(var(--status-bar-height) + 13px); //如果不可以可以按照这个加或者减一些高度
		// padding-top: env(safe-area-inset-top);
		/* 避免灵动岛遮挡 */
		box-sizing: border-box;

		display: flex;
		align-items: center;

		>image {
			// width: 528rpx;
			height: 260rpx;
		}

		.back {
			padding: 30rpx;
			// padding-left: 30rpx;
			// width: 22rpx;
			// height: 22rpx;
		}
	}

	.time {
		text-align: center;
		font-size: 18rpx;
		color: #999;
	}

	.avatar {
		margin-top: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		>image {
			margin-right: 5rpx;
			width: 80rpx;
			height: 80rpx;
		}

		.mainTitle {
			padding-left: 10rpx;
			color: rgb(0, 0, 0);
			font-size: 14rpx;
			font-weight: 600;
			line-height: 1.2;
			text-align: center;
		}
	}

	.title {
		padding: 12rpx 0 20rpx;
		color: rgb(0, 0, 0);
		font-size: 20rpx;
		font-weight: 600;
		line-height: 24rpx;
		text-align: left;
	}

	.count {
		// padding: 0 0 6rpx 100rpx;
		text-align: center;
		border-bottom: 1rpx solid rgb(208, 222, 233);
		box-sizing: border-box;
	}

	.nav {
		margin-top: 20rpx;
		display: flex;

		.isActive {
			.icon {
				display: none;
			}

			>text {
				color: #000;
			}
		}

		>view {
			flex: 1;
			padding: 16rpx 0;
			width: fit-content;
			color: rgb(102, 102, 102);
			font-size: 16rpx;
			font-weight: 600;
			line-height: 16rpx;
			text-align: center;

			>text {
				position: relative;
			}

			.icon {
				position: absolute;
				bottom: 6rpx;
				left: -30rpx;
				width: 30rpx;
				height: 30rpx;
				background: rgb(255, 218, 103);
				border-radius: 50%;
				color: rgb(255, 255, 255);
				font-size: 15rpx;
				font-weight: 600;
				line-height: 30rpx;
				text-align: center;
			}
		}
	}
	

</style>